"""
Copyright (c) 2009, Devon Scott-Tunkin - released under New BSD licence
this file was part of the cocograph tiled map editor
http://code.google.com/p/devdev-python/
"""
import pyglet

import cocos
from cocos.director import director

import kytten


class DialogNode(cocos.batch.BatchableNode):
    def __init__(self, dialog=None):
        super(DialogNode, self).__init__()
        self.dialog = dialog

    def set_batch(self, batch, group=None, z=0):
        super(DialogNode, self).set_batch(batch, group)
        if self.dialog is not None:
            self.dialog.batch = self.batch
            self.dialog.group = self.group

    def delete(self, dialog=None):
        self.dialog.teardown()
        super(DialogNode, self).on_exit()
        # note: BatchableNode.remove will call CocosNode.remove which will call
        # on_exit, so probably the line above is not necesary
        self.parent.remove(self)

    def draw(self):
        pass

class DialogLayer(cocos.layer.Layer):
    is_event_handler = True
    def __init__(self, dialog=None):
        super(DialogLayer, self).__init__()
        self.anchor = (0.0, 0.0)
        self.dialogs_by_name = {}
        self.batchnode = cocos.batch.BatchNode()
        #self.batchnode.position = 50,100
        self.add(self.batchnode)
        #self.batch = pyglet.graphics.Batch()
        #self.group = pyglet.graphics.OrderedGroup(0)
        director.window.register_event_type('on_update')        
        def update(dt):
            director.window.dispatch_event('on_update', dt)
        self.schedule(update)

    def has_dialog(self):
        return len(self.batchnode.children)>0

    def add_dialog(self, dialog_node, name=None):
        if dialog_node is not None:
            self.batchnode.add(dialog_node)
            if name is not None:
                self.dialogs_by_name[name] = dialog_node

    def remove_dialog(self, target):
        if isinstance(target, DialogNode):
            dialog = target
        else:
            name = target
            dialog = self.dialogs_by_name.pop(name)
        dialog.delete()
        
    def on_key_press(self, symbol, modifiers):
        for c in self.batchnode.get_children():
            if c.dialog.focus and hasattr(c.dialog ,'on_key_press'):
                return True

    def on_key_release(self, symbol, modifiers):
        for c in self.batchnode.get_children():
            if c.dialog.on_key_release(symbol, modifiers):
                return True

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        for c in self.batchnode.get_children():
            if c.dialog.on_mouse_drag(x, y, dx, dy, buttons, modifiers) \
            or c.dialog.focus != None:
                return True 

    def on_mouse_motion(self, x, y, dx, dy):
        for c in self.batchnode.get_children():
            c.dialog.on_mouse_motion(x, y, dx, dy)
            if c.dialog.hover is not None:
                return True
            else:
                c.dialog.set_focus(None)

    def on_mouse_press(self, x, y, button, modifiers):
        was_handled = False
        for c in self.batchnode.get_children():
            if c.dialog.on_mouse_press(x, y, button, modifiers):
                was_handled = True
        return was_handled
            #~ c.dialog.set_wheel_hint(None)
            #~ c.dialog.set_wheel_target(None)

    def on_mouse_release(self, x, y, button, modifiers):
        was_handled = False
        for c in self.batchnode.get_children():
            if c.dialog.on_mouse_release(x, y, button, modifiers):
                was_handled = True  
        return was_handled

    def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
        for c in self.batchnode.get_children():
            if c.dialog.on_mouse_scroll(x, y, scroll_x, scroll_y):
                return True

    def on_text(self, text):
         for c in self.batchnode.get_children():
            if c.dialog.focus and hasattr(c.dialog.focus, 'on_text'):
                return True 

    def on_text_motion(self, motion):
        for c in self.batchnode.get_children():
            if c.dialog.focus and hasattr(c.dialog.focus, 
                                          'on_text_motion'):
                return True

    def on_text_motion_select(self, motion):
        for c in self.batchnode.get_children():
            if c.dialog.focus and hasattr(c.dialog.focus, 
                                          'on_text_motion_select'):
                return True  

def test_dialog():
    class TestLayer(cocos.layer.Layer):
        is_event_handler = True
        def on_key_press(self, symbol, modifiers):
            scene = self.get_ancestor(cocos.scene.Scene)
            if scene.dialog_layer.has_dialog():
                return
            print 'scene on_key_press'
            if symbol==pyglet.window.key.RETURN: # checkear que dialog == None?
                self.get_ancestor(cocos.scene.Scene).pop_up_dialog()

    class TestDialogNode(DialogNode):
        def __init__(self):
            theme = kytten.Theme('../data/ui_theme', override={
                "gui_color": [64, 128, 255, 255],
                "font_size": 14
            })

            super(TestDialogNode,self).__init__(
                kytten.Dialog(
                    window=director.window,
                    anchor=kytten.ANCHOR_LEFT, # if comented out, centered in window
                    theme=theme,
                    on_escape=self.on_escape,
                    content=(
                        kytten.Frame(
                            kytten.Menu(options=[
                                "campaign",
                                "coop",
                                "side by side",
                                "hard competition"
                                ],
                                align=kytten.HALIGN_LEFT,
                                on_select=self.on_test_select
                            )
                        )
                    ),
                ) #/kytten dialog
            )
            #
        def on_test_select(self, choice):
            print 'select:',choice


        def on_escape(self,k_dialog):
            self.delete()

    class TestScene(cocos.scene.Scene):
        def __init__(self):
            super(TestScene,self).__init__()
            self.anchor = (0.0, 0.0)
            self.add(TestLayer())
            self.dialog_layer = DialogLayer()
            self.add(self.dialog_layer)
            
        def pop_up_dialog(self):
            dialog = TestDialogNode()
            self.dialog_layer.add_dialog(dialog)
            
    director.init(width=640, height=480, resizable=True, 
                  do_not_scale=True, caption='use return to pop-up dialog')
    director.show_FPS = True
    pyglet.gl.glClearColor(.3, .3, .3, 1)
    scene = TestScene()
    director.run(scene)

if __name__ == '__main__':
    test_dialog()
